package com.sky.config;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * 当Rabbitmq中不存在相关交换机及队列时，会自动创建
 */
@Configuration
public class RabbitmqBeanConfig {

    /**
     * 订单延迟队列
     **/
    @Bean
    public Queue orderDelayQueue(){
        Map<String, Object> arguments = new HashMap<>();
        // 消息过期之后转发的交换机
        arguments.put("x-dead-letter-exchange", "order-event-exchange");
        // 消息过期之后转发的路由键
        arguments.put("x-dead-letter-routing-key", "order.release.order");
        // 消息过期时间(1分钟)
        arguments.put("x-message-ttl", 60000);
        Queue queue = new Queue("order.delay.queue", true, false, false,arguments);
        return queue;
    }

    /**
     * 订单解锁队列
     **/
    @Bean
    public Queue orderReleaseQueue(){
        return new Queue("order.release.queue", true, false, false);
    }

    /**
     * 订单交换机
     **/
    @Bean
    public Exchange orderEventExchange(){
        return new TopicExchange("order-event-exchange", true, false);
    }

    /**
     *  交换机"order.event.exchange"通过路由键"order.create.order"传递信息到队列"order.delay.queue"
     **/
    @Bean
    public Binding orderCreateExchangeBinding(){
        return new Binding("order.delay.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.create.order", null);
    }

    /**
     *  交换机"order.event.exchange"通过路由键"order.release.order"传递信息到队列"order.release.queue"
     **/
    @Bean
    public Binding orderReleaseExchangeBinding(){
        return new Binding("order.release.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.release.order", null);
    }

    @RabbitListener(queues = "order.release.queue")
    public void listener(String msg, Channel channel, Message message) throws IOException {
        System.out.println("监听到消息：" + msg);
        // 手动消息确认接收
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
